<?php

// use \Firebase\JWT\JWT;
use think\Exception;

// 应用公共文件

/**
 * 成功数据格式输出
 * @param string $message
 * @param null $data
 * @return \think\response\Json
 */
function success($code = 0, $msg = "操作成功", $data = [], $httpStatus = 200, $header = [], $options = [])
{
	$result = [
		'code'	=> $code,
		'msg'	=> $msg
	];
    if (is_object($data)) {
        $data = $data->toArray();
    }
    $result['data'] = $data;
    $response = \think\Response::create($result, "json", $httpStatus, $header, $options);
    throw new \think\exception\HttpResponseException($response);
}

/**
 * 失败数据格式输出
 */
function fail ($code = 201, $msg = "", $httpStatus = 200, $header = [], $options = [])
{
	$result = [
        'code'  => $code,
        'msg'   => $msg
    ];
    $response = \think\Response::create($result, "json", $httpStatus, $header, $options);
    throw new \think\exception\HttpResponseException($response);
}



function error($code = 101, $msg = "", $httpStatus = 200)
{
	$result = [
		'code'	=> $code,
		'msg'	=> $msg
	];
	return json($result, $httpStatus);
}

/**
 * 获取客户端ip地址
 * @return bool
 */
function getIp ()
{
	$ip = false;
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
		$ip = $_SERVER['HTTP_CLIENT_IP']; 
	}
}

/**
 * 递归生成分类树
 * getTree
 * @author: buddha
 * @date 2020/8/1 15:08
 * @param array $item 遍历数组
 * @param int $pid
 * @param string $sub
 * @param int $level
 * @param int $type 获取层级
 * @return array
 */
function getTree($item = [], $type = 3, $pid = 0, $sub = 'children', $level = 1)
{
    $data = [];
    foreach($item as $key => $val){
        if($val['pid'] == $pid && $level <= $type){
            $val['level'] = $level;
            $res = getTree($item, $type, $val['id'], $sub, $level + 1);
            if ($res) {
                $val[$sub] = $res;
            }
            $data[] = $val;
        }
    }
    return $data;
}

/**
 * 生成随机key
 * @param int $length
 * @return bool|string
 */
function randString($length = 6) {
    $str = md5(time());
    $key = substr($str, 3, $length);
    return $key;
}


/**
 * 字符串转换为数组
 * @param  string $str  要分割的字符串
 * @param  string $glue 分割符
 */
function str2arr($str = '', $glue = ',') {
	if (gettype($str) === "string") {
		$str = str_replace('"', '', $str);
		// 去除大括号
		$data = explode($glue, trim(trim($str, "{"), "}"));
		$array = array();
		for ($i=0; $i < count($data); $i++) {
			$array[explode(":", $data[$i])[0]] = explode(":", $data[$i])[1];
		}
		return $array;
	} else {
		return array();
	}
}






// 获取随机数
function getRandom($len)
{
	return substr(md5(time()), rand(1,10), $len);
}